package cn.yutong.system.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yutong.framework.UserCache;
import io.swagger.annotations.Api;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.google.common.base.Strings;

import cn.yutong.framework.RestResponse;
import cn.yutong.framework.util.ServletUtils;
import cn.yutong.system.entity.InviteCode;
import cn.yutong.system.entity.User;
import cn.yutong.system.service.IInviteCodeService;
import cn.yutong.system.service.IUserService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author: lnexin@aliyun.com
 */
@RestController
@Api(tags = "用户注册登录")
public class LoginController {
    private static Logger logger = LogManager.getLogger(LoginController.class);

    @ApiIgnore
    @GetMapping("/login")
    public String loginTakeUri(HttpServletRequest request, HttpServletResponse response) {
        if (ServletUtils.isAjaxRequest(request)) {
            return ServletUtils.renderString(response, "{\"ret\":-1,\"msg\":\"未登录/登录超时![ajax-loing]\"}");
        }
        return "login";
    }

    @Autowired
    IUserService userService;

    /**
     * !!!!!!!!!!!!!!!!!!!!!注意！!!!!!!!!!!!!!!! shiro 的from登录是不走这里的
     *
     * @param username
     * @param password
     * @return
     */

    @ApiOperation(value = "用户登录接口", notes = "登录需要提交参数")
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    @ResponseBody
    public RestResponse login(@RequestParam("username") String username, @RequestParam("password") String password) {
        logger.debug("用户登录:username:{}, password:{}", username, password);
        logger.info("用户登录:username:{}", username);
        try {
            User user = userService.selectUsername(username);
            String dbPass = user.getPassword();
            if (password.equals(dbPass)) {
                UserCache.add2UserMap(user.getUid());
                return RestResponse.success("登录成功", user);
            } else {
                System.out.println("登陆失败！");
                return RestResponse.failure("登录失败", "密码错误");
            }
        } catch (Exception e) {
            return RestResponse.failure("登录失败", StringUtils.isNotEmpty(e.getMessage()) ? e.getMessage() : "认证失败");
        }
    }

    @GetMapping("/noAuth")
    public String noAuth() {
        return "error/noAuth";
    }

    @GetMapping("/logout")
    public String logout() {
        return "login";
    }

    @Autowired
    IInviteCodeService codeService;

    @PostMapping("/register")
    @ApiOperation("注册接口")
    @Transactional
    public RestResponse register(
            @ApiParam("账户名") @RequestParam("account") String username,
            @ApiParam("密码") @RequestParam("password") String password,
            @ApiParam("名称") @RequestParam("name") String name,
            @ApiParam("手机号") @RequestParam("phone") String phone,
            @ApiParam("邀请码") @RequestParam("inviteCode") String inviteCode) {
        User u = userService.selectUsername(username);
        if (u != null) {
            return RestResponse.newEntity(403, "用户名已存在，请更换用户名", "注册失败");
        }

        Wrapper<InviteCode> wrapper = new EntityWrapper<>();
        wrapper.eq("code", inviteCode);
        InviteCode code = codeService.selectOne(wrapper);
        if (code == null || Strings.isNullOrEmpty(inviteCode)) {
            return RestResponse.newEntity(401, "邀请码不存在!", "注册失败");
        }
        if (code.getStatus() == 1) {
            return RestResponse.newEntity(402, "邀请码已经被使用!", "注册失败");
        }

        code.setStatus(1);
        codeService.updateById(code);

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setPhone(phone);
        user.setContent(name + "::注册::" + phone);

        boolean insert = userService.insert(user);
        return RestResponse.newEntity(200, "注册成功", user);

    }

}